<template>
  <div>
    <!-- 用户管理页主体部分 -->
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="showadduser">添加用户</el-button>
      </div>
      <div>
        <el-table :data="userlist" border stripe>
          <el-table-column type="index" label="#">
          </el-table-column>
          <el-table-column label="头像" width="61">
            <template slot-scope="scope">
              <img style="width:40px;hight:40px;border-radius: 50%;" :src="scope.row.avatar" alt="avatar">
            </template>
          </el-table-column>
          <el-table-column prop="email" label="账号" width="240">
          </el-table-column>
          <el-table-column prop="nickName" label="昵称">
          </el-table-column>
          <el-table-column label="角色">
            <template slot-scope="scope">
              <div v-if="scope.row.role == 'admin'">
                管理员
              </div>
              <div v-else>普通用户</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <div>
                <div v-if="scope.row.status == '1'">
                  激活
                </div>
                <div v-else>未激活</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="上次登录" width="180">
            <template slot-scope="scope">
              <div>{{scope.row.createTime|dateFormat}}</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="showModifyDialog(scope.row)">修改</el-button>
              <el-button type="danger" size="small" @click="deleteuser(scope.row._id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 修改按钮对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="modifyUserinfoDialogVisible" width="50%" @close="emptyRolesDialog">
      <div class="modifyuserinfo_main">
        <el-form label-position="left" :model="modifyuserinfo" :rules="modifyuserinfoRules" ref="ModifyuserinfoRuleForm" label-width="80px" :hide-required-asterisk="true" class="demo-ruleForm">
          <el-form-item label="UID：">
            <el-input v-model="modifyuserinfo._id" disabled></el-input>
          </el-form-item>
          <el-form-item label="E-Mail：">
            <el-input v-model="modifyuserinfo.email" disabled></el-input>
          </el-form-item>
          <el-form-item label="昵称：" prop="nickName">
            <el-input v-model="modifyuserinfo.nickName"></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="modifyuserinfo.status" placeholder="请选择用户状态">
              <el-option label="激活" value="1"></el-option>
              <el-option label="未激活" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限：">
            <el-select v-model="modifyuserinfo.role" placeholder="请选择用户权限">
              <el-option label="超级管理员" value="admin"></el-option>
              <el-option label="普通用户" value="normal"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyUserinfoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyuserif">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户信息" :visible.sync="addUserDialogVisible" width="50%" @close="addUserDialog">
      <div class="adduser_main">
        <el-form label-position="left" :model="adduserinfo" :rules="adduserinfoRules" ref="adduserinfoRuleForm" label-width="80px" :hide-required-asterisk="true" class="demo-ruleForm">
          <el-form-item label="E-Mail：" prop="email">
            <el-input v-model="adduserinfo.email"></el-input>
          </el-form-item>
          <el-form-item label="昵称：" prop="nickName">
            <el-input v-model="adduserinfo.nickName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="adduserinfo.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="adduserinfo.checkPass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="adduserinfo.status" placeholder="请选择用户状态">
              <el-option label="激活" value="1"></el-option>
              <el-option label="未激活" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="权限：">
            <el-select v-model="adduserinfo.role" placeholder="请选择用户权限">
              <el-option label="超级管理员" value="admin"></el-option>
              <el-option label="普通用户" value="normal"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function() {
    var checkEmail = (rule, value, callback) => {
      const regemail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regemail.test(value)) {
        callback()
      }
      callback(new Error('邮箱输入错误!'))
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.adduserinfo.checkPass !== '') {
          this.$refs.adduserinfoRuleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.adduserinfo.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      userlist: [],
      // 修改用户所用数据
      modifyUserinfoDialogVisible: false,
      modifyuserinfo: {},
      modifyuserinfoRules: {
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 添加用户所用数据
      addUserDialogVisible: false,
      adduserinfo: {
        email: '',
        nickName: '',
        password: '',
        checkPass: '',
        status: '',
        role: ''
      },
      adduserinfoRules: {
        // 用户名验证规则
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 用户昵称
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        // 密码验证规则
        password: [
          { validator: validatePass, trigger: 'blur' },
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ],
        // 确认密码
        checkPass: [
          { validator: validatePass2, trigger: 'blur' },
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getuserlist()
  },
  methods: {
    // 获取用户列表
    async getuserlist() {
      const that = this
      await this.$http({
        method: 'get',
        url: '/users'
      }).then((res) => {
        this.userlist = res.data
        // console.log(res)
        // console.log(this.userlist)
      }).catch((err) => {
        const messg = err.response.data
        that.$message({
          showClose: true,
          message: messg,
          type: 'error'
        })
      })
    },
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // 修改用户对话框回调
    emptyRolesDialog() {
      this.modifyuserinfo = {}
    },
    // 获取信息展示对话框
    async showModifyDialog(data) {
      const that = this
      const uid = data._id
      // console.log(uid)
      await that.$http({
        method: 'get',
        url: '/users/' + uid
      }).then((res) => {
        res.data.status = res.data.status + ''
        that.modifyuserinfo = res.data
        // console.log(res.data)
      }).catch((err) => {
        const messg = err.response.data
        that.$message({
          showClose: true,
          message: messg,
          type: 'error'
        })
      })
      // this.modifyuserinfo = data
      // console.log(that.modifyuserinfo)
      that.modifyUserinfoDialogVisible = true
    },
    // 修改用户
    modifyuserif() {
      this.$refs.ModifyuserinfoRuleForm.validate(async (valid) => {
        if (!valid) return
        const formdata = this.$qs.stringify(this.modifyuserinfo)
        const that = this
        await this.$http({
          method: 'put',
          url: '/users/' + this.modifyuserinfo._id,
          data: formdata
        }).then((res) => {
          // console.log(res)
          that.getuserlist()
          that.$message({
            showClose: true,
            message: '用户信息修改成功',
            type: 'success'
          })
          that.modifyUserinfoDialogVisible = false
        }).catch((err) => {
          const messg = err.response.data
          that.$message({
            showClose: true,
            message: messg,
            type: 'error'
          })
        })
      })
    },

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // 添加用户对话框回调
    addUserDialog() {
      this.adduserinfo = {}
    },
    // 展示添加用户对话框
    showadduser() {
      this.addUserDialogVisible = true
    },
    // 添加用户
    adduser() {
      this.$refs.adduserinfoRuleForm.validate(async (valid) => {
        if (!valid) return
        const creatuserinfo = {
          avatar: this.InitializeAvatar,
          email: this.adduserinfo.email,
          nickName: this.adduserinfo.nickName,
          password: this.adduserinfo.password,
          status: this.adduserinfo.status - 0,
          role: this.adduserinfo.role
        }
        const formdata = this.$qs.stringify(creatuserinfo)
        const that = this
        await this.$http({
          method: 'post',
          url: '/users',
          data: formdata
        }).then((res) => {
          that.getuserlist()
          that.$message({
            showClose: true,
            message: '添加新用户成功！',
            type: 'success'
          })
          that.addUserDialogVisible = false
        }).catch((err) => {
          const messg = err.response.data
          that.$message({
            showClose: true,
            message: messg,
            type: 'error'
          })
        })
      })
    },
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    async deleteuser(uid) {
      const removeInfo = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeInfo !== 'confirm') {
        return this.$message({
          showClose: true,
          message: '删除用户操作已取消！',
          type: 'info'
        })
      } else {
        const res = await this.$http.delete('/users/' + uid)
        if (res.status !== 200) {
          return this.$message({
            showClose: true,
            message: '删除失败！',
            type: 'error'
          })
        }
        this.getuserlist()
        this.$message({
          showClose: true,
          message: '删除成功！',
          type: 'success'
        })
      }
    }
  }
}
</script>

<style scoped>
.modifyuserinfo_main,.adduser_main {
  width: 80%;
  margin: 0 auto;
}
</style>
